package com.dwork.base.mybatis.typehandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

public class StringArrayTypeHandler extends BaseTypeHandler<String[]> {

	@Override
	public void setNonNullParameter(PreparedStatement ps, int i,
			String[] parameter, JdbcType jdbcType) throws SQLException {
		StringBuffer buffer = new StringBuffer();
		
		for (int j = 0; j < parameter.length; j++) {
			if(j != 0 ){
				buffer.append(",");
			}
			buffer.append(parameter[j]);
		}
		ps.setString(i, buffer.toString());
	}
	@Override
	public String[] getNullableResult(ResultSet rs, String columnName)
			throws SQLException {
		String s = rs.getString(columnName);
		if (s != null) {
			String[] ss = s.split(",");
			String[] ints = new String[ss.length];
			for (int i = 0; i < ss.length; i++) {
				ints[i] = new String(ss[i]);
			}
			return ints;
		}
		return null;
	}
	@Override
	public String[] getNullableResult(ResultSet rs, int columnIndex)
			throws SQLException {
		String s = rs.getString(columnIndex);
		if (s != null) {
			String[] ss = s.split(",");
			String[] ints = new String[ss.length];
			for (int i = 0; i < ss.length; i++) {
				ints[i] = new String(ss[i]);
			}
			return ints;
		}
		return null;
	}

	@Override
	public String[] getNullableResult(CallableStatement cs, int columnIndex)
			throws SQLException {
		String s = cs.getString(columnIndex);
		if (s != null) {
			String[] ss = s.split(",");
			String[] ints = new String[ss.length];
			for (int i = 0; i < ss.length; i++) {
				ints[i] = new String(ss[i]);
			}
			return ints;
		}
		return null;
	}

}
